<template>
  <i-card v-draggable="title" v-show="visible" class="note-form">
    <p slot="title" ref="title" style="cursor: move;">
      <i-icon type="document-text"></i-icon>&nbsp;记笔记
    </p>
    <i-form :model="form" :rules="rules" @submit.native.prevent="save()" ref="new-note-form">
      <i-form-item prop="tags">
        <i-checkbox v-model="form.public">分享到笔记广场</i-checkbox>
        <tag-selector label="知识点" :values.sync="form.tags" :subject="subject" :grade="grade"></tag-selector>
      </i-form-item>
      <i-form-item prop="description">
        <i-input :rows="8" placeholder="请输入内容" type="textarea" v-model="form.description"></i-input>
      </i-form-item>
      <i-form-item>
        <i-button html-type="submit" type="primary">保存</i-button>
        <i-button class="margin-left-10" type="default" @click="cacel()">取消</i-button>
      </i-form-item>
    </i-form>
  </i-card>
</template>

<script>
import { mapActions } from 'vuex'
import TagSelector from '../tag-selector'
import { Draggable } from 'draggable-vue-directive'
export default {
  components: {
    TagSelector
  },
  data() {
    return {
      visible: false,
      subject: null,
      grade: null,
      title: {
        handle: null
      },
      form: {
        title: null,
        tags: [],
        description: null,
        courseId: null,
        public: true
      },
      rules: {
        title: {
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        },
        description: {
          required: true,
          message: '请输入内容',
          trigger: 'blur'
        },
        tags: {
          type: 'array',
          required: true,
          message: '请输入相关知识点'
        }
      }
    }
  },
  directives: {
    Draggable
  },
  mounted() {
    this.title.handle = this.$refs['title']
  },
  methods: {
    ...mapActions({
      saveNote: 'saveNote'
    }),
    new(item) {
      this.form.title = item && item.title
      this.form.tags = [].concat(item && item.tags)
      this.form.courseId = item && item.courseId
      this.grade = item && item.grade
      this.subject = item && item.subject
      this.form.id = item && item.id
      this.form.description = item && item.description

      this.visible = true
    },
    save() {
      const that = this
      that.$refs['new-note-form'].validate(valid => {
        if (!valid) return
        that.saveNote({
          form: this.form,
          callback() {
            that.$Message.success('笔记保存成功')
            that.cacel()
          }
        })
      })
    },
    cacel() {
      this.form.courseId = null
      this.form.description = null
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>
.note-form {
  position: absolute;
  top: 100px;
  left: 100px;
  width: 400px;
  z-index: 9999;
  .ivu-card-head {
    cursor: move;
  }
}
</style>
